<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.keyword" placeholder="请输入部门名称" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="filters.sn" placeholder="请输入部门编号" clearable></el-input>
        </el-form-item>
        <el-form-item label="是否启用">
          <el-select v-model="filters.state" placeholder="请选择" clearable>
            <el-option label="启用" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="queryDepts">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd()">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="depts" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="sn" label="部门编号" width="140" sortable>
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="140"  sortable>
      </el-table-column>
      <el-table-column prop="state" label="是否启用" width="140" sortable>
        <template scope="scope"><!-- scope作用 就是用来获取当前行的值 -->
          <!-- v-if v-show-->
          <div v-if="scope.row.state == 0"  slot="reference" >
            <el-tag size="medium" type="danger">禁用</el-tag>
          </div>
          <div v-if="scope.row.state == 1" slot="reference" >
            <el-tag size="medium" type="success">启用</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="manager.username" label="管理员" width="140" sortable>
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" min-width="140" sortable>
      </el-table-column>
      <el-table-column label="操作" >
        <template scope="scope">
          <el-button size="small" @click="handlesave(scope.$index, scope.row,)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 15, 30]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="float:right;">
      </el-pagination>
    </el-col>

    <!--保存界面-->
    <!--
      :visible.sync 控制模态框是否显示

      :rules="saveFormRules"  表单验证的绑定
      prop="sn" 专门用来做表单验证

    -->
    <el-dialog :title="saveTitle" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="saveForm.sn" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="管理员">
          <el-select v-model="saveForm.manager_id" placeholder="请选择">
            <!--
               v-for
               :key 用于去重的  必要唯一 id
               :label 显示你选中的值
               :value 提交后给  v-model赋值
            -->
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item.id">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门">
          <el-cascader v-model="saveForm.parent_id"
                       :options="tree"
                       :props="{
                          checkStrictly:true,
                          label:'name',
                          value:'id',
                       }"
                       clearable></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
export default {
  data() {
    return {
      total: 0,
      currentPage:1,
      pageSize:10,

      depts: [], //列表数据

       //高级查询
      filters: {
        keyword:"",
        sn:"",
        state:"",
      },
      //批量删除用
      sels: [],//列表选中列

      //新增和修改用
      saveFormVisible: false,//编辑界面是否显示
      saveTitle:"",//设置标题  新增或者是编辑
      saveLoading: false, //忙等
      saveFormRules: { //表单的验证
        sn: [
          //   必传         提示信息                失去焦点触发
          { required: true, message: '请输入编号', trigger: 'blur' }
          /* ,{ min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }*/
        ],
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' }
        ]
      },

      employees:[],//存放员工列表的数据
      tree:[],//存放部门树

      //编辑界面数据 form表单
      saveForm: {
        id: null,
        sn:"",
        name: '',
        state: 0,
        manager_id: null,
        parent_id: null,
      },
      //忙等 默认关闭
      listLoading: false,

      addFormVisible: false,//新增界面是否显示
      addLoading: false,
      addFormRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ]
      },
      //新增界面数据
      addForm: {
        name: '',
        sex: -1,
        age: 0,
        birth: '',
        addr: ''
      }

    }
  },
  methods: {
    //当前页的事件
    handleCurrentChange(val) {//自动获取当前页码
      this.currentPage = val;
      this.getdepts();//刷新
    },
    //选择条数的事件
    handleSizeChange(val){//自动获取当前页的条数
      this.pageSize = val
      this.getdepts();//刷新
    },
    queryDepts(){
      this.currentPage = 1
      this.getdepts()
    },
    //获取部门列表
    getdepts() {
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.filters.keyword,
        sn: this.filters.sn,
        state: this.filters.state,
      };
      this.listLoading = true;//开启忙等
      //获取部门列表分页的数据
      this.$http.post("/dept/pagelist",para).then(res=>{
        this.depts = res.data.data
        this.total = res.data.total
        this.listLoading = false;//关闭忙等
      })
    },
    //获取员工列表
    getEmployee(){
      this.$http.get("/emp/list").then(res=>{
        console.log(res)
        this.employees = res.data
      })
    },
    //获取部门树
    getTree(){
      this.$http.get("/dept/tree").then(res=>{
        console.log(res.data)
        this.tree = res.data
      })
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '温馨提示', {
        type: 'warning'//图标设置类型
      }).then(() => {  //确定要做的事情
        this.listLoading = true; //开启忙等
        //发送请求
        this.$http.delete("/dept/"+row.id).then(res=>{
          this.listLoading = false;//关闭忙等
          //判断是否删除成功
          if(res.data.success){
            //弹出提示框
            this.$message({
              message: res.data.msg,
              type: 'success'
            });
            //刷新列表
            this.currentPage = 1
            this.getdepts();//刷新列表
          }else {
            //删除失败 提示信息
            this.$message({
              message: res.data.msg,
              type: 'warning'
            });
          }
        })
      }).catch(() => { //取消要做的事情
      });
    },
    //显示编辑界面
    handlesave: function (index, row) {
      this.saveTitle = "编辑"
      if(this.$refs['saveForm']){
        this.$refs['saveForm'].resetFields();//重置表单验证
      }
      this.saveFormVisible = true;//是否显示
      this.saveForm = Object.assign({}, row); //给表单赋值
    },
    //显示新增界面
    handleAdd: function () {
      this.saveTitle = "新增"
      if(this.$refs['saveForm']){
        this.$refs['saveForm'].resetFields();//重置表单验证
      }
      this.saveForm = {
        id: null,
        sn:"",
        name: '',
        state: 1,
        manager_id: null,
        parent_id: null,
      }
      this.saveFormVisible = true
    },
    //编辑
    saveSubmit: function () {
      this.$refs.saveForm.validate((valid) => {//手动触发验证规则
        if (valid) {
          this.$confirm('确认提交吗？', '温馨提示', {})
              .then(() => {
                this.saveLoading = true;//开启忙的

                //let para = Object.assign({}, this.saveForm);//克隆
                let para = this.saveForm //直接赋值


                if(para.parent_id){
                  if(typeof para.parent_id == "object"){para.parent_id = para.parent_id[para.parent_id.length - 1];
                  }
                }/*else {
                  if (para.dirPath){
                    let dir = para.dirPath.split("/")
                    para.parent_id = dir[dir.length - 2]
                  }
                }*/
                /*console.log(para)*/
                this.$http.put("/dept",para).then(res=>{
                  console.log(res)
                  if(res.data.success){
                    this.saveLoading = false;
                    this.$message({
                      message: res.data.msg,
                      type: 'success'
                    });
                    //重置表单验证
                    this.$refs['saveForm'].resetFields();
                    this.saveFormVisible = false;//关闭模态框
                    this.getdepts();//刷新列表
                  }else {
                    this.$message({
                      message: res.data.msg,
                      type: 'warning'
                    });
                    this.saveLoading = false;
                  }
                })

                // para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
                // savedept(para).then((res) => {
                //   this.saveLoading = false;
                //   //NProgress.done();
                //   this.$message({
                //     message: '提交成功',
                //     type: 'success'
                //   });
                //   this.$refs['saveForm'].resetFields();
                //   this.saveFormVisible = false;
                //   this.getdepts();
                // });
              });
        }
      });
    },

    selsChange: function (sels) {//给多选框绑定事件  如果勾选就获取当前的值
      this.sels = sels;//将选择中的数据赋值给this.sels
    },
    //批量删除
    batchRemove: function () {

      var ids = this.sels.map(item => item.id);//返回一个ids数组   tostring 直接把数组变为字符串

      this.$confirm('确认删除选中记录吗？', '温馨提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;//开启忙等

        this.$http.patch("/dept/del",ids).then(res=>{
          this.listLoading = false;
          //判断是否删除成功
          if(res.data.success){
            //弹出提示框
            this.$message({
              message: res.data.msg,
              type: 'success'
            });
            //刷新列表
            this.currentPage = 1
            this.getdepts();//刷新列表
          }else {
            //删除失败 提示信息
            this.$message({
              message: res.data.msg,
              type: 'warning'
            });
          }
        })
      }).catch(() => {

      });
    }
  },
  mounted() {
    this.getdepts();
    this.getEmployee();
    this.getTree();
  }
}
</script>

<style scoped>

</style>